// stores/counter.js
import {
	defineStore
} from 'pinia';
import config from '../config.js';
import request from '../request.js';
import tool from '../tool.js';

let front = ''
// #ifdef H5
front = location.pathname //兼容一个服务多个项目 内存冲突问题
// #endif
let getStorage = (text) => uni.getStorageSync(front + text)
const install = defineStore('store', {
	state: () => {
		return { //存放状态
			"shopToken": getStorage('shopToken') || '',

			"userInfo": getStorage('userInfo') || '',
			"config": getStorage('config') || '',
			"token": getStorage('token') || '',
			"city": getStorage('city') || '',

			"isclose": false,
			"client_id": ''
		};
	},
	actions: {
		setData(key, data = '') {
			// uni.setStorage({
			// 	key: front + key,
			// 	data
			// })
			uni.setStorageSync(front + key, data)
			this[key] = data
			uni.$emit('updata:' + key, data)
		},
		getData(key) {
			return this[key] ?? getStorage(key) ?? ''
		},

		async chat_init() { //监听类只执行一次 需要放到app.vue onLaunch //this.$store.chat_init()
			// 监听 WebSocket 连接打开事件
			uni.onSocketOpen((res) => {
				console.log('Socket 连接已打开！', res)
				this.isclose = true;
			});
			// 监听 WebSocket 连接关闭事件
			uni.onSocketClose((res) => {
				console.log('Socket 已关闭！', res)
				this.isclose = false;
			});
			// 监听WebSocket错误。
			uni.onSocketError((err) => {
				console.log(err);
			});
			// 监听WebSocket发送消息。
			uni.onSocketMessage((res) => {
				let data = JSON.parse(res.data);
				uni.$emit('chat:' + data.type, data);
				if (data.type == 'init') { // 初始化
					this.client_id = data.client_id
					// 绑定 client_id 到 uid
					request('/platform/message/shake', {
						'client_id': data.client_id
					})
					
				} else if (data.type == 'ping') { // 心跳回执
					// 通过 WebSocket 连接发送数据
					uni.sendSocketMessage({
						data: '{"type":"pong"}'
					});
				} else if (data.type == 'chat') {
					// 全局通知
					// uni.$emit('$onChat', data);
				} else if (data.type == 'msg') {
					// 全局通知
					tool.msg(data.msg)
				} else if (data.type == 'url') {
					// 全局跳转
					tool.advJump(data)
				} else if (data.type == 'voice') {
					this.voice(data)
				} else {
					// console.log("未知消息: " + JSON.stringify(data))
				}
			});
			this.chat_start()
		},
		async chat_start() {
			if (!this.token) return
			// 如果已连接，关闭重新连接
			if (this.isclose) uni.closeSocket()
			// 在接口内获取链接
			let socketurl = this.config?.socketurl || config.socketurl || ''
			if (!socketurl) {
				uni.$off('updata:config', this.chat_start)
				uni.$once('updata:config', this.chat_start)
				return
			}
			console.log('Socket地址:', socketurl);
			// 创建一个 WebSocket 连接
			uni.connectSocket({
				url: socketurl
			});
		},
		chat_close() {
			uni.closeSocket(); //关闭WebSocket
		},
		voice(data) {
			let voice = uni.createInnerAudioContext();
			voice.autoplay = true;
			voice.src = data.msg
			voice.onEnded(voice.destroy); //播放结束
			voice.play() //开始播放
			uni.vibrateLong() //震动
			// if (data.data) uni.createPushMessage(data.data)
		},
	},
});

export default install